package com.dy.yunying.biz.service.cps.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.cps.CpsNodeData;
import com.dy.yunying.api.cps.CpsUserAuthPackReq;
import com.dy.yunying.api.cps.CpsUserPack;
import com.dy.yunying.api.entity.SubChannelInfoDO;
import com.dy.yunying.api.req.WanAppChlReq;
import com.dy.yunying.biz.dao.manage.ext.PromotionChannelDOMapperExt;
import com.dy.yunying.biz.service.cps.CpsUserAuthPackService;
import com.dy.yunying.biz.dao.manage.cps.CpsUserAuthPackMapper;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.dy.yunying.biz.service.manage.GameChannelPackService;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import jodd.introspector.MapperFunction;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * cps用户分包授权
 * @author sunyq
 */
@Service
public class CpsUserAuthPackServiceImpl extends ServiceImpl<CpsUserAuthPackMapper, CpsUserPack>
    implements CpsUserAuthPackService{

	@Autowired
	private AdRoleUserService adRoleUserService;

	@Autowired
	private GameChannelPackService gameChannelPackService;

	@Autowired
	private PromotionChannelDOMapperExt promotionChannelDOMapperExt;

	@Autowired
	private CpsUserAuthPackMapper cpsUserAuthPackMapper;

	@Override
	public List<CpsNodeData> selectChannelTree(Integer userId) {
		WanAppChlReq req = new WanAppChlReq();
		if (SecurityUtils.getRoles().contains(1)) {
			req.setIsSys(1);
		} else {
			//
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);
			req.setUserList(roleUserIdList);
		}

		//子渠道信息
		List<SubChannelInfoDO> subChannelInfoDOS = gameChannelPackService.queryChlInfoListByAuth(req);
		//去重后的主渠道编码集合
		Set<String> parentCodeSet = new HashSet<>();
		if (CollectionUtils.isNotEmpty(subChannelInfoDOS)){
			for (SubChannelInfoDO subChannelInfoDO : subChannelInfoDOS) {
				parentCodeSet.add(subChannelInfoDO.getParentCode());
			}
		}
		if (CollectionUtils.isEmpty(parentCodeSet)){
			return Lists.newArrayList();
		}
		//查询所有主渠道信息
		List<CpsNodeData> channelList = promotionChannelDOMapperExt.selectByConditions(parentCodeSet);

		//查询当前用户授权
		List<CpsUserPack> cpsUserPacks = baseMapper.selectList(Wrappers.<CpsUserPack>lambdaQuery().eq(CpsUserPack::getUserId, userId));
		List<String> cpsSubChl = null ;
		List<String> cpsAppChl = null ;
		if (CollectionUtils.isNotEmpty(cpsUserPacks)){
			cpsSubChl = cpsUserPacks.stream().map(new MapperFunction<CpsUserPack, String>() {
				@Override
				public String apply(CpsUserPack cpsUserPack) {
					return cpsUserPack.getChl();
				}
			}).collect(Collectors.toList());
			cpsAppChl = cpsUserPacks.stream().map(new MapperFunction<CpsUserPack, String>() {
				@Override
				public String apply(CpsUserPack cpsUserPack) {
					return cpsUserPack.getAppChl();
				}
			}).collect(Collectors.toList());
		}
		//
		if (CollectionUtils.isNotEmpty(channelList)) {
			//
			List<CpsNodeData> subChannelList;
			for (CpsNodeData node : channelList) {
				subChannelList = subChannelInfoDOS.stream().filter(n -> StringUtils.isNotBlank(n.getParentCode()) && n.getParentCode().equals(node.getNodeId())).map((MapperFunction<SubChannelInfoDO, CpsNodeData>) subChannelInfoDO -> {
					CpsNodeData nodeData = new CpsNodeData();
					nodeData.setNodeId(subChannelInfoDO.getSubChl());
					nodeData.setNodeName(subChannelInfoDO.getSubChlName());
					return nodeData;
				}).distinct().collect(Collectors.toList());
				boolean allSubChannelChecked = true;
				if (CollectionUtils.isNotEmpty(subChannelList)){
					for (CpsNodeData subNode : subChannelList) {
						boolean allAppChlChecked = true;
						//当前权限下的所有的分包渠道
						List<SubChannelInfoDO> allAppChlInfoList = subChannelInfoDOS.stream().filter(n -> StringUtils.isNotBlank(n.getSubChl()) && n.getSubChl().equals(subNode.getNodeId())).collect(Collectors.toList());
						List<CpsNodeData> appChlList = new ArrayList<>();
						for (SubChannelInfoDO subChannelInfoDO : allAppChlInfoList) {
							CpsNodeData nodeData = new CpsNodeData();
							nodeData.setNodeId(subChannelInfoDO.getAppChl());
							nodeData.setNodeName(subChannelInfoDO.getAppChlName());
							if (CollectionUtils.isNotEmpty(cpsAppChl)){
								if (cpsAppChl.contains(subChannelInfoDO.getAppChl())) {
									nodeData.setChecked(true);
								}
							}
							//TODO 判断当前子渠道下的分包渠道是否都被选中
//							if (CollectionUtils.isNotEmpty(cpsAppChl)){
//								if (!allAppChlChecked){
//									continue;
//								}
//								if (!cpsAppChl.contains(subNode.getNodeId())){
//									allAppChlChecked = false;
//								}
//							} else {
//								allAppChlChecked = false;
//							}
							appChlList.add(nodeData);
						}
//						if (allAppChlChecked){
//							subNode.setChecked(true);
//						}
						if (CollectionUtils.isNotEmpty(appChlList)){
							subNode.setChildNodeList(appChlList);
						}
//						//判断主渠道下的所有子渠道都被选中
//						if (CollectionUtils.isNotEmpty(cpsSubChl)){
//							if (!allSubChannelChecked){
//								continue;
//							}
//							if (!cpsSubChl.contains(subNode.getNodeId())){
//								allSubChannelChecked = false;
//							}
//						} else {
//							allSubChannelChecked = false;
//						}
					}
//					if (allSubChannelChecked){
//						node.setChecked(true);
//					}
					node.setChildNodeList(subChannelList);
					node.setParentChl(true);
				}
			}
		}
		return channelList;
	}

	@Override
	public R saveAuthPack(CpsUserAuthPackReq cpsUserAuthPackReq) {
		//先删除
		Integer cpsUserId = cpsUserAuthPackReq.getUserId();
		baseMapper.delete(Wrappers.<CpsUserPack>lambdaQuery().eq(CpsUserPack::getUserId, cpsUserId));
		List<String> channelList = cpsUserAuthPackReq.getChannelList();
		if (CollectionUtils.isNotEmpty(channelList)){
			// 处理
			List<CpsUserPack> list = cpsUserAuthPackMapper.selectChannalInfoByAppChl(channelList);

			if (CollectionUtils.isNotEmpty(list)){
				for (CpsUserPack cpsUserPack : list) {
					cpsUserPack.setUserId(cpsUserId);
					cpsUserPack.setCreateId(SecurityUtils.getUser().getId().longValue());
					cpsUserPack.setCreateTime(new Date());
				}
				saveBatch(list);
			}
		}
		return R.ok();
	}


}




